<template>
    <div class="fillcontain">
        <head-top></head-top>
        <div class="table_container">
            <el-table
                :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)"
                highlight-current-row
                style="width: 100%">
                <el-table-column
                  type="index"
                  width="100">
                </el-table-column>
                <el-table-column
                  prop="updateTime"
                  label="注册日期"
                  width="280">
                  <template slot-scope="props">
                    <span>{{ props.row.updateTime| dateFmt('YYYY-MM-DD HH:mm:ss') }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="realName"
                  label="用户姓名"
                  width="220">
                  <template slot-scope="props">
                    <span>{{ props.row.realName }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="userPhone"
                  label="手机号"
                  width="220">
                  <template slot-scope="props">
                    <span>{{ props.row.userPhone }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="购买记录">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      @click="buyHistory(scope.row)">查看</el-button>
                  </template>
                </el-table-column>
            </el-table>
           <div class="pagination">
                       <el-pagination
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           :current-page="currentPage"
                           :page-sizes="[5, 10, 20, 40]"
                           :page-size="pagesize"
                           layout="total, sizes,prev, pager, next"
                           :total="tableData.length"
                           prev-text="上一页"
                           next-text="下一页">
                       </el-pagination>
                   </div>
            <el-dialog title="购买记录" v-model="dialogFormVisible">
                <!-- <el-form :model="selectTable">
                    <el-form-item label="设备名称" label-width="100px">
                        <el-input v-model="selectTable.user_name" auto-complete="off"></el-input>
                    </el-form-item>
                </el-form> -->
                <el-table
                    :data="tableData"
                    highlight-current-row
                    style="width: 100%">
                    <el-table-column
                      type="index"
                      width="50">
                    </el-table-column>
                    <el-table-column
                      prop="createdTime"
                      label="日期"
                      width="270">
                      <template slot-scope="props">
                        <span>{{ props.row.createdTime| dateFmt('YYYY-MM-DD HH:mm:ss') }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="userEmail"
                      label="产品"
                      width="200">
                      <template slot-scope="props">
                        <span>{{ props.row.userEmail }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="userRole"
                      label="价格"
                      width="">
                      <template slot-scope="props">
                        <span>{{ props.row.userRole }}</span>
                      </template>
                    </el-table-column>

                </el-table>
            </el-dialog>
        </div>
    </div>
</template>

<script>
   import headTop from '../components/headTop'
   import {baseUrl, baseImgPath} from '@/config/env'
   import {getusers, getEquipsCount, getMenu, updateuser, deleteEquip, getResturantDetail, getMenuById} from '@/api/getData'
   export default {
       data(){
           return {
               posterURI:this.$host+"/zk/uploadFileServer/uploadFolder",
               selectValue: "",
               baseUrl,
               baseImgPath,
               restaurant_id: null,
               city: {},
               offset: 0,
               limit: 3,
               count: 0,
               tableData: [],
                currentPage: 1, //默认显示页面为1
                               pagesize: 5, //    每页的数据条数
               selectTable: {},
               dialogFormVisible: false,
               menuOptions: [],
               selectMenu: {},
               selectIndex: null,
               specsForm: {
   	          	specs: '',
   	          	packing_fee: 0,
   	          	price: 20,
   	        },
               specsFormrules: {
   	        	specs: [
   					{ required: true, message: '请输入规格', trigger: 'blur' },
   				],
   	        },
               fileList: [],
   	        specsFormVisible: false,
               expendRow: [],
           }
       },
       mounted(){
               this.getusers();
           },

       created(){
       	this.restaurant_id = this.$route.query.restaurant_id;
           this.initData();
       },
       computed: {
           headers() {
               return{
                   "Authorization": localStorage.getItem('token')
               }
           },

       	specs: function (){
       		let specs = [];
       		if (this.selectTable.specEquips) {
           		this.selectTable.specEquips.forEach(item => {
           			specs.push({
           				specs: item.specs_name,
           				packing_fee: item.packing_fee,
           				price: item.price,
           			})
           		})
       		}
       		return specs
       	}
       },
   	components: {
   		headTop,
   	},
       filters: {
           limitWord(value) {
               if (!value) {
                   value = "";
               } else if (value.length > 10) {
                   value = value.slice(0, 10) + "...";
               }
               return value + "...";


           },


       },

       methods: {
           // handleSuccess(res){
           //     this.selectTable.equip_img = res.data;
           //     console.log(res.data)

           // },
           // handleRemove(file, fileList) {
           //     console.log(file, fileList);
           // },
           // handlePreview(file,) {
           //     console.log(file);
           // },
           // changeOpen(){
           //     if(this.selectTable.is_del!=null)
           //     {
           //         if(this.selectTable.is_del==0)
           //         {
           //             this.selectTable.is_del=1;
           //         }
           //         else{
           //             this.selectTable.is_del = 0;
           //         }

           //     }


           // },
           // addEquip(index, row){
           //     this.$router.push({ path: 'addEquip', query: { restaurant_id: row.id }})
           // },
           async initData(){
               console.log("我进来了====》》》");
               this.getusers();

               try{
                   const countData = await getusersCount({restaurant_id: this.restaurant_id});
                   if (countData.status == 1) {
                       this.count = countData.count;
                   }else{
                       throw new Error('获取数据失败');
                   }

               }catch(err){
                   console.log('获取数据失败', err);
               }
           },
           // async getMenu(){
           // 	this.menuOptions = [];
           //     try{
           //         const menu = await getMenu({restaurant_id: this.selectTable.restaurant_id, allMenu: true});
           //         menu.forEach((item, index) => {
           //             this.menuOptions.push({
           //             	label: item.name,
           //             	value: item.id,
           //             	index,
           //             })
           //         })
           //     }catch(err){
           //         console.log('获取商品失败', err);
           //     }
           // },
           async getusers(){
               var that = this
                   this.$axios.get(this.$host2+"/zk/user/",{
                       headers: {
                           "Authorization": localStorage.getItem('token')

                       }
                   }).then(
                       res=>{
                           that.tableData = res.data.data;
                           console.log(that.tableData)


                       }
                   ).catch(error=>console.log(error));

           },
           tableRowClassName(row, index) {
   	        if (index === 1) {
   	        	return 'info-row';
   	        } else if (index === 3) {
   	        	return 'positive-row';
   	        }
   	        return '';
   	    },
   	    addspecs(){
   			this.specs.push({...this.specsForm});
   			this.specsForm.specs = '';
   			this.specsForm.packing_fee = 0;
   			this.specsForm.price = 20;
   			this.specsFormVisible = false;
   		},
   		deleteSpecs(index){
   			this.specs.splice(index, 1);
   		},
           //每页下拉显示数据
                       handleSizeChange: function(size) {
                           this.pagesize = size;
                           /*console.log(this.pagesize) */
                       },
                       //点击第几页
                       handleCurrentChange: function(currentPage) {
                           this.currentPage = currentPage;
                           /*console.log(this.currentPage) */
                       },
           expand(row, status){
           	if (status) {
           		this.getSelectItemData(row)
           	}else{
                   const index = this.expendRow.indexOf(row.index);
                   this.expendRow.splice(index, 1)
               }
           },
           buyHistory(row) {
               console.log(row.product_id)
           	this.getSelectItemData(row, 'edit')
               this.dialogFormVisible = true;
               this.selectTable =JSON.parse(JSON.stringify(row));
               console.log(this.selectTable)
           },
           async getSelectItemData(row, type){
           	const restaurant = await getResturantDetail(row.restaurant_id);
           	const category = await getMenuById(row.category_id)
               this.selectTable = {...row, ...{restaurant_name: restaurant.name, restaurant_address: restaurant.address, category_name: category.name}};

               this.selectMenu = {label: category.name, value: row.category_id}
               this.tableData.splice(row.index, 1, {...this.selectTable});
               this.$nextTick(() => {
                   this.expendRow.push(row.index);
               })
               if (type == 'edit' && this.restaurant_id != row.restaurant_id) {
               	this.getMenu();
               }
           },
           handleSelect(index){
           	this.selectIndex = index;
           	this.selectMenu = this.menuOptions[index];
           },
           async handleDelete(index, row) {
               try{
                   const res = await deleteEquip(row.item_id);
                   if (res.status == 1) {
                       this.$message({
                           type: 'success',
                           message: '删除商品成功'
                       });
                       this.tableData.splice(index, 1);
                   }else{
                       throw new Error(res.message)
                   }
               }catch(err){
                   this.$message({
                       type: 'error',
                       message: err.message
                   });
                   console.log('删除商品失败')
               }
           },
           handleServiceAvatarScucess(res, file) {
               if (res.status == 1) {
                   this.selectTable.image_path = res.image_path;
               }else{
                   this.$message.error('上传图片失败！');
               }
           },
           beforeAvatarUpload(file) {
               const isRightType = (file.type === 'image/jpeg') || (file.type === 'image/png');
               const isLt2M = file.size / 1024 / 1024 < 2;

               if (!isRightType) {
                   this.$message.error('上传头像图片只能是 JPG 格式!');
               }
               if (!isLt2M) {
                   this.$message.error('上传头像图片大小不能超过 2MB!');
               }
               return isRightType && isLt2M;
           },
           async updateiser(){
               this.dialogFormVisible = false;
               try{
                   this.$axios({
                       method: 'put',
                       url: this.$host2+`/zk/user/`,
                       headers:{
                           "Authorization": localStorage.getItem('token')
                       },
                       params: {

                           userName: this.selectTable.user_name,
                           userPhone: this.selectTable.user_phone,
                           equipIntroduce: this.selectTable.equip_introduce,
                           equipPrice: this.selectTable.equip_price,
                           isDel: this.selectTable.is_del,
                           equipInventory: this.selectTable.equip_inventory,


                       },}).then(res=>{
                           if(res.data.code==200){
                               this.$message({
                                   type: 'success',
                                   message: '更新成功'
                               });
                               this.getusers();
                           }else{
                               this.$message({
                                   type: 'error',
                                   message: res.data.msg
                               });
                           }
                   }).catch(error=>{
                       console.log(error)
                       this.$message({
                           type: 'error',
                           message: res.data.msg
                       });
                   });

               }catch(err){
                   console.log('更新套餐信息失败', err);
               }
           },
       },
   }
</script>

<style lang="less">
	@import '../style/mixin';
    .table_container{
        padding: 20px;
    }
</style>
